package com.xiaoniu.timer.impl;

import com.xiaoniu.timer.Log;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Created by sweet on 2017/11/10.
 * ---------------------------
 */
public class FileLogImpl implements Log {
//
//  public static void main(String[] args) throws IOException {
//    String p = "pom2.xml";
//    new File(p).renameTo(new File("pom2.xml"+LocalDate.now()));
//  }

  @Override
  public void info(String info) {
    write("INFO", info);
  }

  @Override
  public void debug(String debug) {
    write("DEBUG", debug);
  }

  @Override
  public void error(String error) {
    write("ERROR", error);
  }

  private void write(String level, String info) {
    try {
      String fileName = "timer-log.log";
      Path path = Paths.get(fileName);
      if (Files.exists(path)) {
        if (Files.size(path) >= 10486545) {
          new File(fileName).renameTo(new File(LocalDate.now()+"_"+fileName));
          Files.createFile(path);
        } else {
          Files.write(Paths.get(fileName), (LocalDateTime.now() + " ==> " + level + " ==> " + info + "\n").getBytes(), StandardOpenOption.APPEND);
        }
      } else {
        Files.createFile(path);
      }
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    }
  }
}
